package org.rcy.framework.utils.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpRequestUtils {

    // Send a GET request
    public static HttpResponse sendGet(String url, Map<String, String> headers) throws Exception {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                connection.setRequestProperty(header.getKey(), header.getValue());
            }
        }

        return getResponse(connection);
    }

    // Send a POST request
    public static HttpResponse sendPost(String url, String body, Map<String, String> headers) throws Exception {
        return sendRequestWithBody(url, "POST", body, headers);
    }

    // Send a PUT request
    public static HttpResponse sendPut(String url, String body, Map<String, String> headers) throws Exception {
        return sendRequestWithBody(url, "PUT", body, headers);
    }

    // Internal method for POST and PUT requests
    private static HttpResponse sendRequestWithBody(String url, String method, String body, Map<String, String> headers) throws Exception {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod(method);
        connection.setDoOutput(true);

        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                connection.setRequestProperty(header.getKey(), header.getValue());
            }
        }

        if (body != null && !body.isEmpty()) {
            try (OutputStream os = connection.getOutputStream()) {
                os.write(body.getBytes());
                os.flush();
            }
        }

        return getResponse(connection);
    }

    // Handle the response
    private static HttpResponse getResponse(HttpURLConnection connection) throws Exception {
        int status = connection.getResponseCode();
        BufferedReader reader;
        HttpResponse httpResponse = new HttpResponse();
        if (status >= 200 && status < 300) {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }

        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        connection.disconnect();
        httpResponse.setCode(status);
        httpResponse.setRespStr(response.toString());
        return httpResponse;
    }
}